import path from 'path'
import express from 'express'
import http from 'http'
import favicon from 'serve-favicon'
import { Server } from 'socket.io'
import { get } from '../common/conf'
import runSocket from './io'
import { instrument } from '@socket.io/admin-ui'

const setSocket = () => {
  const app = express()
  const server = http.createServer(app)
  const io = new Server(server, {
    cors: {
      origin: ['https://admin.socket.io'],
      credentials: true,
    },
  })
  const host = process.env.HOST || 'localhost'
  const portSocket = get('socket.port')

  instrument(io, {
    auth: {
      type: 'basic',
      username: 'admin',
      password: '$2a$12$XMvNxB8QCKu5g8YY6mOV9ubfrmQ84hCdKXrcjFW6aahUWwMzWaUrq' // https://bcrypt-generator.com/ encrypted with bcrypt
    },
    mode: 'development'
  })

  server.listen(portSocket, () => {
    console.log(`Socket Bingo ==> @ http://${host}:${portSocket}`)
  })

  const publicDir = path.join(__dirname, '../../public')
  const staticDir = path.join(__dirname, '../../public/static')
  const viewDir = path.join(__dirname, 'views')

  app.use(express.static(publicDir))
  app.use(favicon(path.join(publicDir, 'favicon.ico')))
  app.set('views', viewDir)

  app.get('/welcome', (req, res) => {
    res.set({ 'Content-Type': 'text/html' })
    res.sendFile(viewDir + '/welcome.html')
  })

  // app.get('/draw', (req, res) => {
  //   res.send('<h1>Welcome Socket Server</h1>')
  // })

  const socketData = {
    online: {
      onlineUsers: {},
      onlineCount: 0,
    },
    draw: {
      drawUsers: {},
      drawCount: 0,
    },
    chat: {
      chatPublic: {
        users: {},
        count: {
          value: 0
        }
      },
      chatRooms: {},
      chatPrivate: {},
    },
  }

  runSocket(io, socketData)
}

export default setSocket
